package com.controller;

import com.bean.*;
import com.bean.dangBean.Balance;
import com.bean.dangBean.Consumer;
import com.service.*;
import com.util.PageAssistant;
import com.util.QueryAssistant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 销售模块
 */
@Controller
public class SalesOrderController {

    @Autowired
    private CashierOrderRecordService cashierOrderRecordService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private MarketServices marketServices;
    @Autowired
    private CommodityService commodityService;
    @Autowired
    private ConsumerService consumerService;
    @Autowired
    private SalesReturnRecordService salesReturnRecordService;
    @Autowired
    private BalanceService balanceService;

    /**
     * 分页查询订单列表
     * @param model
     * @return
     */
    @RequestMapping("searchOrder")
    public String queryByPage(Model model, QueryAssistant queryAssistant, PageAssistant<CashierOrderRecord> paCash){
        System.out.println(">>>query searchOrder");
        System.out.println(queryAssistant);
        System.out.println(paCash);
        Map<String, Object> map = new HashMap<>();
        //添加查询参数
        Date startT=null;
        Date endT=null;
        try {
            if(queryAssistant.getStartTime() !=null && !queryAssistant.getStartTime().equals("")) {
                startT = new SimpleDateFormat("yyyy-MM-dd").parse(queryAssistant.getStartTime());
            }
            if(queryAssistant.getEndTime() != null && !queryAssistant.getEndTime().equals("")){
                endT = new SimpleDateFormat("yyyy-MM-dd").parse(queryAssistant.getEndTime());
                //设置时分秒为23：59：59
                endT.setHours(23);
                endT.setMinutes(59);
                endT.setSeconds(59);
            }
        } catch (ParseException e) {
//            e.printStackTrace();
        }
        System.out.println(startT);
        System.out.println(endT);
        if(queryAssistant.getOrderId() != null && queryAssistant.getOrderId() !="" ){
            map.put("orderId", Long.parseLong(queryAssistant.getOrderId()));
        }
        map.put("startTime", startT);
        map.put("endTime",endT);

        //查询总记录数
        paCash.setCount(cashierOrderRecordService.count(map));

        //设置分页参数
        map.put("start", paCash.getStart());
        map.put("size", paCash.getSize());

        //查询当前页内容
        paCash.setItems(cashierOrderRecordService.query(map));

        model.addAttribute("paCash",paCash);
        return "sales/searchOrder";
    }

    /**
     * 查询单项订单详情
     * @param model
     * @return
     */
    @RequestMapping("sales/orderDetail/page")
    public String cashierOrderDetail(Model model, Long orderId,String prevUrl){
        //销售订单详情列表页
        System.out.println(">>> sales/cashierOrderDetail-page");
        System.out.println(orderId);
        System.out.println(prevUrl);
        Map<String, Object> map = new HashMap<>();
        map.put("orderId",orderId);

        //查询是否由此订单
        List<CashierOrderRecord> cashierOrderRecordList = cashierOrderRecordService.find(new CashierOrderRecord(orderId));
        if(cashierOrderRecordList.size() == 1){
            CashierOrderRecord cashInfo = cashierOrderRecordList.get(0);
            model.addAttribute("cashInfo",cashInfo);
            List<ShoppingCart> shoppingCartList = shoppingCartService.query(map);
            //保存商品信息
            for(ShoppingCart sh: shoppingCartList){
//                //根据商品Id查询,查商品销售价
                Market market = marketServices.find(new Market(sh.getProductId())).get(0);
                sh.setMarket(market);
                //根据商品Id查询,查商品名称
                Commodity commodity = commodityService.find(new Commodity(sh.getProductId())).get(0);
                sh.getMarket().setCommodity(commodity);
            }
            model.addAttribute("shoppingCartList",shoppingCartList);
            model.addAttribute("orderId",orderId);

            //计算订单实际总金额
            Double money = 0.00;
            for(ShoppingCart sh: shoppingCartList){
                money = money + sh.getPrice();
            }
            model.addAttribute("money",money);

            if(prevUrl.equals("cashierOrder")){
                return "sales/orderDetail";
            }else if(prevUrl.equals("salesReturn")){
                //查询此订单id的退单记录
                map.clear();
                map.put("orderId",orderId);
                List<SalesReturnRecord> salesReturnRecordList = salesReturnRecordService.query(map);
                model.addAttribute("salesReturnRecordList",salesReturnRecordList);
                return "salesReturn/searchAndModify";
            }else{
                System.out.println("走了这里？？");
                return "";
            }
        }else{
            return "salesReturn/searchAndModifyError";
        }
    }
    /**
     * 查询消费者VIP消息
     * @param model
     * @param consumer
     * @return
     */
    @ResponseBody
    @RequestMapping("findVIP")
    public Map<String, Object> findVIP(Model model, Consumer consumer){
        System.out.println(">>> findVIP ");
        System.out.println(consumer);

        Map<String, Object> map = new HashMap<>();
        //查询
        List<Consumer> consumers = consumerService.find(consumer);
        if(consumers.size() == 1){
            map.put("consumerInfo",consumers.get(0));
        }
        return map;
    }
    /**
     * 新增购物车订单
     * @param model
     * @param session
     * @param shoppingCart
     * @return
     */
    @ResponseBody
    @RequestMapping("addShoppingCart")
    public Map<String, Object>  addShoppingCart(Model model, HttpSession session, ShoppingCart shoppingCart){
        System.out.println(">>> addShoppingCart ");
        System.out.println(shoppingCart);

        Map<String, Object> map = new HashMap<>();
        //判断查询的商品ID存在，查超市库存表
        List<Market> markets = marketServices.find(new Market(shoppingCart.getProductId()));
        if(markets.size() == 1){
            //判断订单id是否存在
            String orderId = (String) session.getAttribute("orderId");
            if(orderId == null||orderId.equals("")){
                //生成一个订单id 直接由时间构成
                orderId = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                //保存在session里面
                session.setAttribute("orderId",orderId);
            }
            //根据商品Id查询,查商品名称
            Commodity commodity = commodityService.find(new Commodity(shoppingCart.getProductId())).get(0);
            //商品存在则创建一条购物车数据
            ShoppingCart shoppingCartInfo = new ShoppingCart();
            shoppingCartInfo.setOrderId(Long.parseLong(orderId));//保存订单id
            shoppingCartInfo.setProductId(shoppingCart.getProductId());//商品id
            shoppingCartInfo.setNumber(1);//商品数量
            //判断商品是否参加活动
            if(markets.get(0).getState() == 1){
                //商品处于活动状态
                shoppingCartInfo.setUnitPrice(markets.get(0).getDiscountPrice());//保存折扣价到购物车信息
            }else {
                //商品不参加活动
                shoppingCartInfo.setUnitPrice(markets.get(0).getPrice());//保存正常销售价到购物车信息
            }
            shoppingCartInfo.setCost(commodity.getPrice());//保存进价
            shoppingCartInfo.setPrice(shoppingCartInfo.getUnitPrice()*shoppingCartInfo.getNumber());//保存商品订单金额
            shoppingCartInfo.setProfit((shoppingCartInfo.getUnitPrice()-commodity.getPrice())*shoppingCartInfo.getNumber());//保存收益
            //保存商品订单状态
            shoppingCartInfo.setState(0);
            //保存购物车数据到数据库
            System.out.println(shoppingCartInfo);
            shoppingCartService.save(shoppingCartInfo);

            //获取保存成功的数据id
            int id = shoppingCartService.find(shoppingCartInfo).get(0).getId();
            shoppingCartInfo.setId(id);

            //保存商品数据
            map.put("marketInfo",markets.get(0));
            map.put("shoppingCartInfo",shoppingCartInfo);
            map.put("name",commodity.getName());
        }else{
            map.put("msg",false);
        }
        return map;
    }

    /**
     * 保存订单
     * @return
     */
    @ResponseBody
    @RequestMapping("saveOrder")
    public Map<String, Object> saveOrder(Model model, HttpSession session, String totalMoney,String orderMoney,String orderId){
        System.out.println(">>> save cashierOrder");
        System.out.println(orderMoney);//结算金额，可能是原金额，可能是VIP金额
        System.out.println(totalMoney);//订单原总金额
        System.out.println(orderId);

        CashierOrderRecord cashierOrderRecord = new CashierOrderRecord();

        cashierOrderRecord.setOrderId(Long.parseLong(orderId));
        if(Double.parseDouble(orderMoney) == -1){
            orderMoney = totalMoney;
        }
        cashierOrderRecord.setOrderMoney(Double.parseDouble(orderMoney));

        Map<String, Object> map = new HashMap<>();
        map.put("orderId",Long.parseLong(orderId));
        //查询购物车订单的收益
        List<ShoppingCart> shoppingCartList = shoppingCartService.query(map);
        //循环计算收益
        Double profits = 0.00;
        Double money = 0.00;
        for(ShoppingCart sh: shoppingCartList){
            profits = profits + sh.getProfit();
            money = money + sh.getPrice();
        }
        System.out.println(money);
//        map.put("money",money);
        //保存
        cashierOrderRecord.setProfits(profits);//保存收益
        cashierOrderRecord.setCreateTime(new Date());//保存订单时间
        int save = cashierOrderRecordService.save(cashierOrderRecord);
        //增加超市账户余额
        Map<String, Object> mapBalance = new HashMap<>();
        List<Balance> balanceList = balanceService.query(mapBalance);//查询所有取最近的那一个
        if(balanceList.size() != 0){
            balanceService.save(new Balance(cashierOrderRecord.getOrderMoney()+balanceList.get(0).getBalance(),new Date()));//保存余额
        }else{
            balanceService.save(new Balance(cashierOrderRecord.getOrderMoney()+0,new Date()));//保存余额
        }
        //扣减商品库存
        for(ShoppingCart sh: shoppingCartList){
            Market market = marketServices.find(new Market(sh.getProductId())).get(0);
            marketServices.modify(new Market(market.getId(),market.getAmount()-sh.getNumber()));
        }
        if(save == 1){
            session.removeAttribute("orderId");
            map.put("state",true);
            try {
                FileWriter fw = new FileWriter(orderId+".txt",true);
                BufferedWriter bw = new BufferedWriter(fw);
                //2. 生成订单发票
                StringBuilder line =new StringBuilder(
                        "------------------------------　　欢迎您的光临　　------------------------------　\n" +
                                "　                店名：xxx超市  ：交易号："+cashierOrderRecord.getOrderId()+"\n" +
                                "　           商品名称　           商品数量　    商品单价　     商品数量　     商品金额\n");
                //循环添加商品信息
                for(ShoppingCart sh: shoppingCartList){
                    //根据商品Id查询,查商品名称
                    Commodity commodity = commodityService.find(new Commodity(sh.getProductId())).get(0);
                    line.append("　           "+commodity.getName()+"　           "+sh.getNumber()+"　     "+sh.getUnitPrice()+
                            "　     "+sh.getNumber()+"　     "+sh.getPrice()+"\n");
                }
                line.append(
                        "-------------------------------------------------------------------------------\n" +
                                "合计金额："+totalMoney+"　　实收金额："+orderMoney+"　　\n" +
                                "交易时间："+cashierOrderRecord.getCreateTime()+"\n" +
                                "　                 退换货时凭此发票办理，谢谢惠顾，欢迎再次光临！\n ");

                //写入输出流
                bw.write(line.toString());
                //写入换行符
                bw.newLine();
                //刷新字符缓冲区
                bw.flush();
                //4. 关闭资源
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            map.put("state",false);
        }
        return map;
    }


    /**
     * 更改某个购物车订单数据
     * @param model
     * @param session
     * @param shoppingCart
     * @return
     */
    @ResponseBody
    @RequestMapping("modifyShoppingCart")
    public Map<String, Object> modifyShoppingCart(Model model, HttpSession session, ShoppingCart shoppingCart){
        System.out.println(">>> modifyShoppingCart ");
        System.out.println(shoppingCart);
        //查询购物车数据
        ShoppingCart sh = shoppingCartService.find(shoppingCart).get(0);

        //判断更改的是数量还是状态
        if(shoppingCart.getNumber() !=1 && shoppingCart.getNumber()!=null){
            //根据商品Id查询,查商品进价
            Commodity commodity = commodityService.find(new Commodity(shoppingCart.getProductId())).get(0);
            //如果是数量，需要更改两个变量
            shoppingCart.setPrice(sh.getUnitPrice()*shoppingCart.getNumber());//保存商品订单金额
            shoppingCart.setProfit((sh.getUnitPrice()-commodity.getPrice())*shoppingCart.getNumber());//保存收益
        }
        //更改
        int i = shoppingCartService.modify(shoppingCart);
        Map<String, Object> map = new HashMap<>();
        if(i == 1){
            map.put("modifyState",true);
        }else{
            map.put("modifyState",false);
        }
        return map;
    }

    /**
     * 删除购物车订单
     * @param shoppingCart
     * @return
     */
    @ResponseBody
    @RequestMapping("deleteShoppingCart")
    public Map<String, Object> deleteShoppingCart(ShoppingCart shoppingCart){
        System.out.println(">>> deleteShoppingCart ");
        System.out.println(shoppingCart);
        Map<String, Object> map = new HashMap<>();

        int i= 0;
        if(shoppingCart.getId() != null && !shoppingCart.getId().equals("")){
            //删除
            i = shoppingCartService.remove(shoppingCart);

        }else if(shoppingCart.getOrderId() != null && !shoppingCart.getOrderId().equals("")){
//            System.out.println("进来了orderid");
            //查询所有orderid的订单
            List<ShoppingCart> shoppingCartList = shoppingCartService.find(shoppingCart);
            for(ShoppingCart sh: shoppingCartList){
                //删除
                i = shoppingCartService.remove(sh);
            }
        }
        System.out.println("出来了orderid");
        if(i == 1){
            map.put("msg","删除成功");
        }else{
            map.put("msg","删除失败");
        }
        return map;
    }

}
